<template>
    <el-scrollbar class="mb-2">
        <div class="mx-4 mt-2 mb-4 star-list">
            <div
                class="rounded-lg pt-4 pb-1 px-3 item"
                v-for="(item, index) in star.all"
                :key="index"
                @click="router.push(`/star/list/${item}`)"
            >
                <!-- 收藏封面 -->
                <div class="rounded icon pa-3">
                    <!-- 音符图标 -->
                    <v-icon size="100px">mdi-music</v-icon>

                    <!-- 按钮列 -->
                    <div class="pa-4 button-row">
                        <!-- 播放按钮 -->
                        <div class="rounded-circle pa-1 button" @click="playStar(item, $event)">
                            <v-icon size="30px">mdi-play-outline</v-icon>
                            <v-tooltip activator="parent" location="bottom">播放</v-tooltip>
                        </div>

                        <!-- 删除按钮 -->
                        <div class="rounded-circle pa-1 button" @click="deleteStar(item, $event)">
                            <v-icon size="30px">mdi-delete-outline</v-icon>
                            <v-tooltip activator="parent" location="bottom">删除</v-tooltip>
                        </div>

                        <!-- 重命名按钮 -->
                        <div class="rounded-circle pa-1 button" @click="renameStar(item, $event)">
                            <v-icon size="30px">mdi-rename-outline</v-icon>
                            <v-tooltip activator="parent" location="bottom">重命名</v-tooltip>
                        </div>

                        <!-- 添加按钮 -->
                        <div class="rounded-circle pa-1 button" @click="addToPlaylist(item, $event)">
                            <v-icon size="30px">mdi-plus</v-icon>
                            <v-tooltip activator="parent" location="bottom">添加到播放列表</v-tooltip>
                        </div>
                    </div>
                </div>

                <!-- 收藏列表名 -->
                <div class="mt-1 title">
                    {{ item }}
                </div>
            </div>

            <!-- 添加新收藏列表按钮 -->
            <div class="rounded-lg pt-4 pb-1 px-3 item" @click="addStarlist">
                <div class="rounded icon pa-3">
                    <v-icon size="100px">mdi-plus</v-icon>
                </div>

                <div class="mt-1 title">添加新收藏列表</div>
            </div>
        </div>

        <confirm-dialog
            v-model="dialogState"
            :title="dialogTitle"
            @confirm="toConfirmDialog"
            @cancel="dialogState = false"
        >
            <!-- 删除确认 -->
            <p v-if="dialogKind === DialogKind.Delete" class="my-6">确认删除收藏列表 “{{ dialogTarget }}” 吗？</p>

            <!-- 重命名确认 -->
            <!-- 添加新的收藏列表 -->
            <v-text-field v-else class="mt-6 mb-4" v-model="dialogText" label="收藏列表名">
                <template #append-inner>
                    <v-fade-transition>
                        <span
                            v-if="dialogText !== dialogTarget"
                            style="cursor: pointer"
                            @click="dialogText = dialogTarget"
                        >
                            <v-icon>mdi-undo-variant</v-icon>
                            <v-tooltip activator="parent" location="bottom">撤回</v-tooltip>
                        </span>
                    </v-fade-transition>
                </template>
            </v-text-field>
        </confirm-dialog>
    </el-scrollbar>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { Playlist } from "@/lib/playlist";
import { injectMessageState } from "@/lib/view";
import useStarStore from "@/store/star";
import usePlaylistStore from "@/store/playlist";
import ConfirmDialog from "@/components/public/dialog/ConfirmDialog.vue";

const router = useRouter();

const star = useStarStore();
const playlist = usePlaylistStore();

// 对话框状态
enum DialogKind {
    /**
     * 删除
     */
    Delete,
    /**
     * 重命名
     */
    Rename,
    /**
     * 新建
     */
    New,
}
const dialogState = ref(false);
const dialogKind = ref(DialogKind.Delete);
const dialogTitle = computed(() => {
    switch (dialogKind.value) {
        case DialogKind.Delete:
            return "删除收藏列表";
        case DialogKind.Rename:
            return "重命名收藏列表";
        case DialogKind.New:
            return "添加新收藏列表";
    }
});
const dialogTarget = ref("");
const dialogText = ref("");

// 全局消息状态
const messageState = injectMessageState();

/**
 * 播放收藏列表
 * @param name 收藏列表名
 * @param event 事件
 */
async function playStar(name: string, event?: MouseEvent) {
    // 阻止事件冒泡
    event?.stopPropagation();

    // 读取收藏列表
    const starlist = await star.load(name);
    if (starlist === undefined) {
        messageState.visible = true;
        messageState.text = `读取收藏列表 “${name}” 失败`;
        return;
    }

    // 记录 shuffle
    const shuffle = playlist.shuffle;

    // 播放收藏列表
    try {
        // 替换
        await Playlist.save(starlist, "focus", "indexes", "items", "shuffle");
        await playlist.load();

        // 恢复 shuffle
        if (shuffle) {
            await playlist.toggleShuffle();
        }

        // 播放
        await playlist.togglePause();
    } catch (error) {
        messageState.visible = true;
        messageState.text = `播放收藏列表 “${name}” 失败`;
        return;
    }
}

/**
 * 删除收藏列表
 * @param name 收藏列表名
 * @param event 事件
 */
function deleteStar(name: string, event?: MouseEvent) {
    // 阻止事件冒泡
    event?.stopPropagation();

    // 设置要删除的收藏列表名
    dialogKind.value = DialogKind.Delete;
    dialogTarget.value = name;
    dialogState.value = true;
}

/**
 * 重命名收藏列表
 * @param name 收藏列表名
 * @param event 事件
 */
function renameStar(name: string, event?: MouseEvent) {
    // 阻止事件冒泡
    event?.stopPropagation();

    // 设置要重命名的收藏列表名
    dialogKind.value = DialogKind.Rename;
    dialogTarget.value = name;
    dialogText.value = name;
    dialogState.value = true;
}

/**
 * 添加收藏列表到播放列表
 * @param name 收藏列表名
 * @param $event 事件
 */
async function addToPlaylist(name: string, $event?: MouseEvent) {
    // 阻止事件冒泡
    $event?.stopPropagation();

    // 读取收藏列表
    const starlist = await star.load(name);
    if (starlist === undefined) {
        messageState.visible = true;
        messageState.text = `读取收藏列表 “${name}” 失败`;
        return;
    }

    // 添加到播放列表
    try {
        await playlist.insert(...starlist.items);
    } catch (error) {
        messageState.visible = true;
        messageState.text = `添加收藏列表 “${name}” 到播放列表失败`;
    }
}

/**
 * 添加新收藏列表
 */
function addStarlist() {
    dialogKind.value = DialogKind.New;
    dialogText.value = "";
    dialogTarget.value = "";
    dialogState.value = true;
}

/**
 * 确认对话框
 */
async function toConfirmDialog() {
    switch (dialogKind.value) {
        case DialogKind.Delete: {
            // 关闭对话框
            dialogState.value = false;

            // 删除收藏列表
            try {
                if (!(await star.remove(dialogTarget.value))) {
                    throw new Error();
                }
                messageState.visible = true;
                messageState.text = `删除收藏列表 “${dialogTarget.value}” 成功`;
            } catch (error) {
                messageState.visible = true;
                messageState.text = `删除收藏列表 “${dialogTarget.value}” 失败`;
            }

            break;
        }
        case DialogKind.Rename: {
            // 判断是否为空
            if (dialogText.value === "") {
                messageState.visible = true;
                messageState.text = "收藏列表名不能为空";
                return;
            }

            // 判断是否与原名相同
            if (dialogText.value === dialogTarget.value) {
                messageState.visible = true;
                messageState.text = "收藏列表名不能与原名相同";
                return;
            }

            // 关闭对话框
            dialogState.value = false;

            // 重命名收藏列表
            try {
                if (!(await star.rename(dialogTarget.value, dialogText.value))) {
                    throw new Error();
                }
                messageState.visible = true;
                messageState.text = `重命名收藏列表 “${dialogTarget.value}” 到 “${dialogText.value}” 成功`;
            } catch (error) {
                messageState.visible = true;
                messageState.text = `重命名收藏列表 “${dialogTarget.value}” 到 “${dialogText.value}” 失败`;
            }

            break;
        }
        case DialogKind.New: {
            // 判断是否为空
            if (dialogText.value === "") {
                messageState.visible = true;
                messageState.text = "收藏列表名不能为空";
                return;
            }

            // 判断是否与已有收藏列表名相同
            if (star.set.has(dialogText.value)) {
                messageState.visible = true;
                messageState.text = "收藏列表名不能与已有收藏列表名相同";
                return;
            }

            // 关闭对话框
            dialogState.value = false;

            // 添加新收藏列表
            try {
                if (!(await star.build(dialogText.value))) {
                    throw new Error();
                }
                messageState.visible = true;
                messageState.text = `添加收藏列表 “${dialogText.value}” 成功`;
            } catch (error) {
                messageState.visible = true;
                messageState.text = `添加收藏列表 “${dialogText.value}” 失败`;
            }

            break;
        }
    }
}
</script>

<style scoped lang="scss">
.star-list {
    overflow-y: scroll;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    row-gap: 16px;
    column-gap: 12px;

    .item {
        max-width: 150px;
        overflow: hidden;

        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        background-color: transparent;
        transition: background-color 0.2s ease-in-out;

        font-size: 14px;
        cursor: pointer;

        &:hover {
            background-color: rgba(var(--v-theme-on-surface-variant), 0.5);

            .icon {
                .button-row {
                    opacity: 1;
                }
            }
        }

        .icon {
            position: relative;
            color: rgba(var(--v-theme-primary), 0.5);
            background-color: rgba(var(--v-theme-primary), 0.2);

            .button-row {
                opacity: 0;
                transition: opacity 0.2s ease;

                width: 100%;
                height: 100%;

                position: absolute;
                left: 0;
                top: 0;

                display: grid;
                align-items: center;
                justify-items: center;
                grid-template-columns: repeat(2, 1fr);

                .button {
                    color: rgb(var(--v-theme-on-background));
                    background-color: rgba(var(--v-theme-on-background), 0.1);
                    transition: background-color 0.2s ease;

                    &:hover {
                        background-color: rgba(var(--v-theme-on-background), 0.25);
                    }
                }
            }
        }

        .title {
            width: 100%;
            overflow: hidden;
            text-wrap: nowrap;
            text-overflow: ellipsis;
            text-align: center;
        }
    }
}
</style>
